const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const db = require('../db'); // 引入数据库连接

// 提交报修请求
router.post('/repair', (req, res) => {
    const { deviceType, faultDescription, urgencyLevel } = req.body;
    const token = req.headers['authorization'];

    if (!token) {
        return res.status(403).json({ message: "没有提供认证信息" });
    }

    // 解析token获取学生信息
    jwt.verify(token, "kio", (err, decoded) => {
        if (err) {
            return res.status(401).json({ message: "认证失败" });
        }

        const studentId = decoded.studentId;
        const status = '未处理'; // 初始状态

        const sql = `INSERT INTO repairs (studentId, deviceType, faultDescription, urgencyLevel, status) 
                 VALUES (?, ?, ?, ?, ?)`;

        db.query(sql, [studentId, deviceType, faultDescription, urgencyLevel, status], (err, results) => {
            if (err) {
                return res.status(500).json({ message: "报修失败" });
            }
            res.json({ message: "报修成功" });
        });
    });
});

// 获取学生报修历史
router.get('/repair/history', (req, res) => {
    const token = req.headers['authorization'];

    if (!token) {
        return res.status(403).json({ message: "没有提供认证信息" });
    }

    // 解析token获取学生信息
    jwt.verify(token, "kio", (err, decoded) => {
        if (err) {
            return res.status(401).json({ message: "认证失败" });
        }

        const studentId = decoded.studentId;

        const sql = 'SELECT * FROM repairs WHERE studentId = ? ORDER BY createdAt DESC';
        db.query(sql, [studentId], (err, results) => {
            if (err) {
                return res.status(500).json({ message: '数据库查询失败' });
            }
            res.json(results);
        });
    });
});

module.exports = router;
